﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.IO;

namespace Nia.Globalization.Tools
{
    class Program
    {
        /// <summary>
        /// args[0]: input file fullpath
        /// args[1]: [optional, default=936] input locale (e.g. 936, 932)
        /// args[2]: [optional, default=65001] output locale (e.g. 936, 932)
        /// 
        /// 936=gb2312
        /// 932=shift-jis
        /// 65000=utf-7
        /// 65001=utf-8
        /// 1200=utf-16=unicode
        /// </summary>
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                ShowUsage();
                return;
            }

            var path = args.First();
            if (!File.Exists(path))
            {
                Console.WriteLine("File does not exist", path);
                return;
            }

            var icp = 936;
            if (args.Length >= 2)
                if (!int.TryParse(args[1], out icp))
                {
                    Console.WriteLine("icp must be a valid codepage number");
                    return;
                }

            var ocp = 65001;
            if (args.Length >= 3)
                if (!int.TryParse(args[2], out ocp))
                {
                    Console.WriteLine("ocp must be a valid codepage number");
                    return;
                }


            Transform(path, icp, ocp);
        }

        private static void Transform(string path, int icp, int ocp)
        {
            var buffer = File.ReadAllText(path, Encoding.GetEncoding(icp));
            File.WriteAllText(path, buffer, Encoding.GetEncoding(ocp));
            Console.WriteLine("Done...");
            Console.ReadLine();
        }

        private static void ShowUsage()
        {
            Console.WriteLine("gb2utf [path] <icp> <ocp>");
            Console.WriteLine(@"sample: gb2utf c:\1.txt");
            Console.WriteLine(@"sample: gb2utf c:\1.txt 936");
            Console.WriteLine(@"sample: gb2utf c:\1.txt 936 65001");
            Console.ReadLine();
        }
    }
}
